import { ref, reactive } from 'vue'

export function useComment() {
  // 批注相关状态
  const latestHighlightElement = ref(null)
  const commentSubmitted = ref(false)
  const comments = ref([])
  const commentIdCounter = ref(0)
  const savedCommentPosition = ref(null)
  const lastScrollTop = ref(0)
  const highlightColors = [
    '#fff5f0', '#E0F5FF', '#FFF1E0', '#E0EFFF', '#F6F2E0', '#E0E0F6',
    '#E6F1D7', '#EAE0F6', '#E0F6E8', '#F6E0EF', '#D6F3F0', '#FFE0E6'
  ]
  const currentColorIndex = ref(0)
  const triggerComment = ref(false)
  const showComments = ref(true) // 控制批注显示隐藏的状态

  // 切换批注显示隐藏
  function toggleCommentsVisibility() {
    showComments.value = !showComments.value
  }

  // 显示所有批注
  function showAllComments() {
    showComments.value = true
  }

  // 隐藏所有批注
  function hideAllComments() {
    showComments.value = false
  }

  // 高亮选中的文本
  function highlightSelectedText(selectionRange, updateContent, setSavedCommentPosition) {
    if (!selectionRange) return
    try {
      const selection = window.getSelection()
      selection.removeAllRanges()
      selection.addRange(selectionRange)
      const range = selectionRange.cloneRange()
      const rect = range.getBoundingClientRect()
      const distanceFromTop = rect.top + window.scrollY
      const highlightSpan = document.createElement('span')
      const highlightClass = `comment-highlight-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
      highlightSpan.className = `comment-highlight ${highlightClass}`
      const currentColor = highlightColors[currentColorIndex.value]
      highlightSpan.style.backgroundColor = currentColor
      highlightSpan.style.color = '#000'
      highlightSpan.style.padding = '2px 4px'
      highlightSpan.style.borderRadius = '3px'
      currentColorIndex.value = (currentColorIndex.value + 1) % highlightColors.length
      const range2 = selectionRange.cloneRange()
      const contents = range2.extractContents()
      highlightSpan.appendChild(contents)
      range2.insertNode(highlightSpan)
      latestHighlightElement.value = highlightSpan
      if (setSavedCommentPosition) {
        setSavedCommentPosition({
          rect,
          distanceFromTop,
          highlightClass,
          highlightColor: currentColor
        })
      }
      selection.removeAllRanges()
      if (updateContent) {
        updateContent()
      }
    } catch (error) {
      console.error('高亮文本时出错:', error)
    }
  }

  // 取消高亮
  function removeHighlight(editorRef, updateContent) {
    if (!editorRef) return
    try {
      const highlightElements = editorRef.querySelectorAll('.comment-highlight')
      if (highlightElements.length === 0) return
      highlightElements.forEach(highlightElement => {
        const textContent = highlightElement.textContent || highlightElement.innerText
        const textNode = document.createTextNode(textContent)
        highlightElement.parentNode.replaceChild(textNode, highlightElement)
      })
      if (updateContent) {
        updateContent()
      }
    } catch (error) {
      console.error('取消高亮时出错:', error)
    }
  }

  // 移除最近高亮
  function removeLatestHighlight(updateContent) {
    try {
      if (!latestHighlightElement.value) return
      if (latestHighlightElement.value.parentNode) {
        const textContent = latestHighlightElement.value.textContent || latestHighlightElement.value.innerText
        const textNode = document.createTextNode(textContent)
        latestHighlightElement.value.parentNode.replaceChild(textNode, latestHighlightElement.value)
        latestHighlightElement.value = null
        if (updateContent) {
          updateContent()
        }
      }
    } catch (error) {
      console.error('移除最近高亮时出错:', error)
    }
  }

  // 处理批注提交
  function handleSubmitComment(comment, createCommentContent, emit) {
    commentSubmitted.value = true
    const commentData = {
      username: comment.username || '匿名用户',
      time: comment.time || new Date().toLocaleString(),
      text: comment.content || comment
    }
    if (savedCommentPosition.value) {
      createCommentContent(
        savedCommentPosition.value.rect,
        savedCommentPosition.value.distanceFromTop,
        commentData,
        savedCommentPosition.value.highlightClass,
        savedCommentPosition.value.highlightColor
      )
      savedCommentPosition.value = null
    }
    if (emit) {
      emit('submit-comment', commentData)
    }
  }

  // 创建批注内容
  function createCommentContent(rect, distanceFromTop, commentData, highlightClass, highlightColor, editorRef) {
    commentIdCounter.value++
    const commentId = `comment-${commentIdCounter.value}`
    const editorRect = editorRef.getBoundingClientRect()
    const relativeTop = distanceFromTop - editorRect.top
    const finalPosition = calculateCommentPosition(relativeTop)
    const colorMap = {
      '#fff5f0': '#F6B18E', '#E0F5FF': '#99D8F6', '#FFF1E0': '#FFCE95', '#E0EFFF': '#83BFFF',
      '#F6F2E0': '#ECD888', '#E0E0F6': '#B4B4FC', '#E6F1D7': '#B7D78A', '#EAE0F6': '#CBA8F6',
      '#E0F6E8': '#8DDBA9', '#F6E0EF': '#EF84CD', '#D6F3F0': '#87D4CC', '#FFE0E6': '#F67D95'
    }
    const color = colorMap[highlightColor]
    const comment = {
      id: commentId,
      username: commentData?.username || '匿名用户',
      time: commentData?.time || new Date().toLocaleString(),
      text: commentData?.text || '这是批注内容示例，可以在这里显示具体的批注信息。',
      originalTop: distanceFromTop,
      highlightClass,
      highlightColor,
      colorIndex: currentColorIndex.value === 0 ? highlightColors.length - 1 : currentColorIndex.value - 1,
      style: {
        position: 'absolute',
        right: '-16vw',
        top: `${finalPosition}px`,
        backgroundColor: `${highlightColor}`,
        borderLeft: `2px solid ${color || '#ddd'}`,
        borderRadius: '4px',
        padding: '8px',
        width: '15.6vw',
        height: '8.3vh',
        zIndex: '1000',
        fontSize: '12px',
        lineHeight: '1.4'
      }
    }
    comments.value.push(comment)
  }

  // 计算批注位置，避免碰撞
  function calculateCommentPosition(initialTop) {
    const commentHeight = 80
    const spacing = 10
    let finalTop = initialTop
    if (comments.value.length >= 10) {
      console.warn('批注数量过多，建议删除一些批注')
    }
    const existingPositions = comments.value.map(comment => ({
      top: parseInt(comment.style.top),
      height: commentHeight
    }))
    let attempts = 0
    const maxAttempts = 10
    while (attempts < maxAttempts) {
      let hasCollision = false
      for (let i = 0; i < existingPositions.length; i++) {
        const existing = existingPositions[i]
        if (isOverlapping(finalTop, existing.top, commentHeight)) {
          hasCollision = true
          finalTop = existing.top + existing.height + spacing
          break
        }
      }
      if (!hasCollision) break
      attempts++
    }
    return finalTop
  }

  // 检查两个批注是否重叠
  function isOverlapping(top1, top2, height) {
    const margin = 5
    return Math.abs(top1 - top2) < height + margin
  }

  // 移除批注
  function removeComment(commentId, editorRef, updateContent) {
    const index = comments.value.findIndex(comment => comment.id === commentId)
    if (index !== -1) {
      const comment = comments.value[index]
      if (comment.highlightClass && editorRef) {
        const highlightElement = editorRef.querySelector(`.${comment.highlightClass}`)
        if (highlightElement) {
          const textContent = highlightElement.textContent || highlightElement.innerText
          const textNode = document.createTextNode(textContent)
          highlightElement.parentNode.replaceChild(textNode, highlightElement)
          if (updateContent) {
            updateContent()
          }
        }
      }
      comments.value.splice(index, 1)
      rearrangeComments(editorRef)
    }
  }

  // 重新排列所有批注，避免重叠
  function rearrangeComments(editorRef) {
    if (comments.value.length <= 1) return
    const commentHeight = 80
    const spacing = 10
    comments.value.sort((a, b) => a.originalTop - b.originalTop)
    for (let i = 0; i < comments.value.length; i++) {
      const comment = comments.value[i]
      const editorRect = editorRef.getBoundingClientRect()
      const relativeTop = comment.originalTop - editorRect.top
      let newTop = relativeTop - 100
      for (let j = 0; j < i; j++) {
        const prevComment = comments.value[j]
        const prevTop = parseInt(prevComment.style.top)
        if (isOverlapping(newTop, prevTop, commentHeight)) {
          newTop = prevTop + commentHeight + spacing
        }
      }
      comment.style.top = `${newTop}px`
    }
  }

  // 鼠标悬停时突出显示对应的高亮区域
  function highlightCommentArea(comment, editorRef) {
    if (!editorRef || !comment.highlightClass) return
    const highlightElement = editorRef.querySelector(`.${comment.highlightClass}`)
    if (highlightElement) {
      highlightElement.style.boxShadow = '0 0 0 2px #007bff, 0 0 0 4px rgba(0, 123, 255, 0.3)'
      highlightElement.style.transform = 'scale(1.02)'
      highlightElement.style.transition = 'all 0.2s ease'
      highlightElement.style.zIndex = '1001'
      scrollToHighlight(highlightElement, editorRef)
    }
  }

  // 鼠标离开时取消突出显示
  function unhighlightCommentArea(comment, editorRef) {
    if (!editorRef || !comment.highlightClass) return
    const highlightElement = editorRef.querySelector(`.${comment.highlightClass}`)
    if (highlightElement) {
      highlightElement.style.boxShadow = ''
      highlightElement.style.transform = ''
      highlightElement.style.transition = ''
      highlightElement.style.zIndex = ''
    }
  }

  // 滚动到高亮区域
  function scrollToHighlight(highlightElement, editorRef) {
    if (!editorRef) return
    const editorRect = editorRef.getBoundingClientRect()
    const highlightRect = highlightElement.getBoundingClientRect()
    const relativeTop = highlightRect.top - editorRect.top
    const editorHeight = editorRect.height
    if (relativeTop < 0 || relativeTop > editorHeight) {
      const scrollTop = editorRef.scrollTop
      const targetScrollTop = scrollTop + relativeTop - editorHeight / 2
      editorRef.scrollTo({
        top: targetScrollTop,
        behavior: 'smooth'
      })
    }
  }

  return {
    latestHighlightElement,
    commentSubmitted,
    comments,
    commentIdCounter,
    savedCommentPosition,
    lastScrollTop,
    highlightColors,
    currentColorIndex,
    triggerComment,
    showComments, // 暴露 showComments 状态
    toggleCommentsVisibility, // 暴露切换批注显示隐藏的方法
    showAllComments, // 暴露显示所有批注的方法
    hideAllComments, // 暴露隐藏所有批注的方法
    highlightSelectedText,
    removeHighlight,
    removeLatestHighlight,
    handleSubmitComment,
    createCommentContent,
    calculateCommentPosition,
    isOverlapping,
    removeComment,
    rearrangeComments,
    highlightCommentArea,
    unhighlightCommentArea,
    scrollToHighlight
  }
}
